package info.techgeek.labs.timer;

import info.techgeek.labs.connection.DAOConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Timer;
import java.util.TimerTask;

public class EggTimer {

	private final Timer timer = new Timer();
	private final int minutes;
	private Connection conn = null;

	public EggTimer(int minutes) {

		this.minutes = minutes;

	}

	public void start() {
		System.out.println("Begin Start");

		PreparedStatement pstmt = null;
		ResultSet rs = null;

//		StringBuilder stringBuilder = new StringBuilder("");
//		stringBuilder.append("select *   from pres_user_sto_temp_2 p1 where p1.user_cod in ( ");
//		stringBuilder.append("select p2.user_cod from pres_user_sto_temp_2 p2  where p2.user_cod in ( ");
//		stringBuilder.append("select p3.user_cod from pres_user_sto_temp_2 p3  where p3.user_cod in ( ");
//		stringBuilder.append("select p4.user_cod from pres_user_sto_temp_2 p4  ) )  ) ");
		
		StringBuilder stringBuilder = new StringBuilder("");
		stringBuilder.append("select *   from pres_user_sto_temp_2 p1 where p1.user_cod in ( ");
		stringBuilder.append("select p2.user_cod from pres_user_sto_temp_2 p2  where p2.user_cod in ( ");
		stringBuilder.append("select p3.user_cod from pres_user_sto_temp_2 p3  )  ) ");
		
		String qryString = stringBuilder.toString();
		try{

			conn= DAOConnectionManager.getInstance().getConnection(null);
			System.out.println(qryString);
			pstmt = conn.prepareStatement(qryString);

			timer.schedule(new TimerTask() {
				public void run() {
					System.out.println("Run ");
					closeConnection();
					timer.cancel();
				}
				private void closeConnection() {
					try {
						System.out.println("Close Connection ");
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}, minutes * 1000);

			long t = System.currentTimeMillis(); 
			rs = pstmt.executeQuery();
			System.out.println("Time Taken using Execute Query :" +( System.currentTimeMillis() -t)); 
			
			timer.cancel();
			
		}catch (SQLException e)
			{
				System.out.println("SqlException");
				e.printStackTrace() ;
			}
			finally
			{
				System.out.println("Finally ");
				DAOConnectionManager.getInstance().closeConnections(rs,pstmt,conn );
			}

			System.out.println("End Start");
		}

	public static void main(String[] args) {
		System.out.println("Start");
		EggTimer eggTimer = new EggTimer(5);
		System.out.println("After Initializatop");
		eggTimer.start();
		System.out.println("End");
	}

}
